﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using CodeBuilder2.View.CB_UserControl.Panel;
using System.ComponentModel;
using System.Windows.Threading;
using CodeBuilder2.Model.Constant;
using CodeBuilder2.View.FloatWindow;
using CodeBuilder2.BLL.ExecuteSQL;
using System.Data;

namespace CodeBuilder2
{
    /// <summary>
    /// MainWnd.xaml 的交互逻辑
    /// </summary>
    public partial class MainWnd : Window
    {
        internal bool IsLogin = false;
        public MainWnd()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 显示登录对话框
        /// </summary>
        void ShowLoginDialog()
        {
            LoginWnd lw = new LoginWnd();
            lw.Owner = this;
            lw.ShowDialog();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ShowLoginDialog();
        }

        private void Button_MouseEnter(object sender, MouseEventArgs e)
        {
            // 为了保证准确获取触发当前事件的按钮在延迟 500 毫秒后的判断鼠标是否在其上的属性的值
            // 这里必须新开一个独立线程，在新线程中进行判断，否则 Button.IsMouseOver 值将始终为 true
            Thread t = new Thread(new ParameterizedThreadStart(this.ShowContentPaneDelay));
            t.Name = "ShowContentPaneDelay";    // 应该是可以方便调试的，不过怎么样利用还没有想到
            t.Start(e);
        }

        /// <summary>
        /// 延迟 500 毫秒后，判断在鼠标划过特定按钮后是否仍然悬停在该按钮上
        /// 如果是，则显示按钮代表的内容面板；如果否，则什么都不做
        /// </summary>
        /// <param name="e">MouseEventArgs 的装箱后的对象</param>
        void ShowContentPaneDelay(object e)
        {
            Thread.Sleep(UIConstant.DELAY_MILLISECOND);
            Button btn = (e as MouseEventArgs).Source as Button;
            if (!btn.IsMouseOver)
                return;
            // 下一句会引发跨线程错误访问异常，但是为什么上面的 btn.IsMouseOver 不会呢？
            //string s = btn.Content.ToString();
            ThreadStart start = delegate()
            {
                dpContainer.Children.Clear();
                //dpContainer.Background = new SolidColorBrush(Colors.LightGray);

                RichPanel rp = new RichPanel();
                rp.PanelName = btn.Content.ToString();
                dpContainer.Children.Add(rp);
                DockPanel.SetDock(rp, Dock.Bottom);
            };
            if (Dispatcher == btn.Dispatcher && Dispatcher == dpContainer.Dispatcher)
                dpContainer.Dispatcher.Invoke(start, DispatcherPriority.ApplicationIdle);

            // 自动隐藏面板

        }

        bool isOut = false;

        private void Button_MouseLeave(object sender, MouseEventArgs e)
        {
            ThreadStart ts = delegate()
            {
                while (!isOut)
                {
                    isOut = !dpContainer.IsMouseOver;
                    Thread.Sleep(200);
                }
                if (isOut)
                {
                    ThreadStart innerTS = delegate()
                    {
                        dpContainer.Children.Clear();
                    };
                    dpContainer.Dispatcher.Invoke(innerTS, DispatcherPriority.SystemIdle);
                    isOut = false;
                }
            };
            Thread t = new Thread(ts);
            t.Start();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //MainWindow mw = new MainWindow();
            //mw.Show();
            SimpleFloatWindow sfWnd = new SimpleFloatWindow();
            sfWnd.Show();
        }

        int sqlTabIndex;
        private void btnCreateSQL_Click(object sender, RoutedEventArgs e)
        {
            TabItem ti = new TabItem();
            ti.Header = "新建 SQL 查询" + (++sqlTabIndex);

            Grid g = new Grid();
            g.ShowGridLines = true;
            RowDefinition rd1 = new RowDefinition();
            rd1.MinHeight = 24;
            RowDefinition rd2 = new RowDefinition();
            rd2.Height = GridLength.Auto;
            RowDefinition rd3 = new RowDefinition();
            rd3.MinHeight = 24;
            g.RowDefinitions.Add(rd1);
            g.RowDefinitions.Add(rd2);
            g.RowDefinitions.Add(rd3);


            TextBox txt = new TextBox();
            txt.Name = "txtSQL";
            txt.AcceptsReturn = true;
            txt.AcceptsTab = true;
            txt.Focusable = true;
            txt.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            txt.TextWrapping = TextWrapping.Wrap;
            // 目前看来，在 WPF 中（WinForm 不确定），当在内存中动态生成 TextBox 等输入类控件，
            // 如果在代码中直接调用其 Focus() 方法是不行的，必须要在控件呈现后（已布局、已呈现且可用于交互时），
            // 再调用 Focus() 才行。典型处理办法如下行所示。
            txt.Loaded += delegate(object txtSender, RoutedEventArgs re) { txt.Focus(); };
            //txt.SetValue(Grid.RowProperty, 2);
            g.Children.Add(txt);

            GridSplitter gs = new GridSplitter();
            gs.VerticalAlignment = VerticalAlignment.Center;
            gs.HorizontalAlignment = HorizontalAlignment.Stretch;
            gs.Height = 5;
            gs.Background = Brushes.Green;
            gs.SetValue(Grid.RowProperty, 1);
            g.Children.Add(gs);

            ti.Content = g;
            tcMain.Items.Add(ti);
            ti.IsSelected = true;

            //txt.Focus();            
            //FocusManager.SetIsFocusScope(ti, true);            
            //Keyboard.Focus(txt);
            //FocusManager.SetFocusedElement(g, txt);
            //txt.Text = txt.Focus().ToString();
        }

        private void btnExecuteSQL_Click(object sender, RoutedEventArgs e)
        {
            Grid g = tcMain.SelectedContent as Grid;
            //TextBox txt = g.FindName("txtSQL") as TextBox;
            TextBox txt = g.Children[0] as TextBox;
            //GridView gv = new GridView();

            ExecuteSQLStringBLL essBll = new ExecuteSQLStringBLL();
            //gv.
            List<string> lst;
            DataSet ds = essBll.ExecuteSQL(txt.SelectedText, out lst);
            txt.Text += "\r\n" + ds.Tables[0].Rows.Count.ToString();
        }
    }
}
